package com.withmiku.world.user.controller;

import com.withmiku.world.user.common.Result;
import com.withmiku.world.user.entity.User;
import com.withmiku.world.user.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;

// TODO
//  1.实现一个通过邮箱找回密码的功能
//  2.允许用户输入自己的个性签名，丰富用户信息（可选）
@RestController
@RequestMapping("/api/user")
public class UserController {
    private final UserService userService;
    @Value("${file.upload-dir:uploads}")
    private String uploadRootPath;

    @Autowired
    public UserController(@Qualifier("userServiceImpl") UserService userService) {
        this.userService = userService;
    }

    // 注册接口
    // TODO
    //  1.需要让用户在注册时需要通过邮箱拿到验证码，输入正确的验证码才能够注册成功
    //  2.用户完成注册后需要向其发送成功的通知/欢迎信（可选）
    @PostMapping("/register")
    public Result<User> register(@RequestParam String username,
                           @RequestParam String password,
                           @RequestParam String email) {
        User user = userService.register(username, password, email);

        return Result.success(200, "注册成功", user);
    }

    // 登录接口
    @PostMapping("/login")
    public Result<String> login(@RequestParam String username,
                        @RequestParam String password) {
        String token = userService.login(username, password);

        return Result.success(200, "登录成功", "token: " + token);
    }

    // 获取用户信息接口
    @GetMapping("/me")
    public Result<User> getCurrentUser(HttpServletRequest request) {
        String username = (String)request.getAttribute("username");
        User user = userService.findByUsername(username);

        return Result.success(200, "获取成功", user);
    }

    // 修改用户信息接口
    @PutMapping("/me")
    public Result updateProfile(@RequestBody User newInfo, HttpServletRequest request) {
        String username = (String)request.getAttribute("username");
        userService.updateProfile(username, newInfo);
        return Result.success(200, "资料更新成功", null);
    }

    // 登出接口
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request) {
        String username = (String)request.getAttribute("username");
        // 前端调用/logout后，只需要清除浏览器里保存的Token即可。
        // 可在这里加入Token黑名单逻辑（可选）


        return Result.success(200, "注销成功，请前端删除本地token", null);
    }

    // 头像上传接口
    @PostMapping("/avatar")
    public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file,
                               HttpServletRequest request) throws IOException {
        String username = (String)request.getAttribute("username");

        if (file.isEmpty()) {
            return Result.error("文件为空");
        }

        // 日期分目录
        LocalDate today = LocalDate.now();
        String datePath = today.getYear() + "/" + today.getMonth() + "/" + today.getDayOfMonth();

        // 最终存储路径
        String uploadDir = uploadRootPath + "/avatars/" + datePath;

        // 保存路径
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 生成唯一文件名(userId_timestamp_originalFilename)
        Long userId = userService.findByUsername(username).getId();
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String originalFilename = file.getOriginalFilename();
        String filename = userId + "_" + timestamp + "_" + originalFilename;

        File dest = new File(uploadDir, filename);
        file.transferTo(dest);

        // 构造访问URL (静态映射为/uploads/**)
        String avatarUrl = "/uploads/avatars/" + datePath + "/" +filename;

        // 更新用户头像字段
        userService.updateAvatar(username, avatarUrl);

        return Result.success(200, "头像上传成功", avatarUrl);
    }

    /**
     * 查看某个用户的主页
     */
    @GetMapping("/{userId}")
    public Result<User> getUserById(@PathVariable Long userId) {
        User user = userService.findById(userId);

        // 在这里屏蔽掉一些隐私信息
        user.setEmail(null);

        return Result.success(200, "查询成功", user);
    }
}
